/**
 * @description:
 * @file: methods.ts
 * @author: Evan
 * @date: 2025.05.19 18:55:39
 * @week: 周一
 * @version: V
 */

import deepClone from '@/utils/deep-clone'

// 获取新表单
export const getNewForms = (forms: ZForms, row?: AnyObject) => {
  if (!forms) return {}
  let newForm: ZForms = {}
  Object.keys(forms).forEach(key => {
    const obj = deepClone(forms[key]) as import('@/components/form/type').ZFormItem
    const userData = obj.userData || {}
    // 判断字段是否只为添加或者编辑
    // 列表数据空 && 编辑
    if (!row && userData.edit) return
    // 列表数据 && 添加
    if (row && userData.add) return

    // 判断字段对应操作的禁用状态
    // 添加则隐藏
    if (!row && userData.addDisabled) return
    // 编辑择禁用
    if (row && userData.editDisabled) obj.disabled = true
    newForm[key] = obj

    // 判断 是否传入行数据
    if (row) {
      let val = row[key]
      // 获取重定向值 格式化
      let redirect = userData.redirect
      let formatter = userData.formatter

      if (redirect) {
        // 对象类型 规避后端不规范
        let key = redirect.split('.')[0]
        if (row[key]) {
          val = eval(`row.${redirect}`)
        }
      }
      if (typeof formatter === 'function') val = formatter(row, val)

      // if (val != void 0) {
      // }
      newForm[key].value = val
    }
  })
  return newForm
}

// 判断函数并执行
export const checkFunction = (
  fn: ((...arg: any[]) => any) | undefined,
  call: (res?: any) => void,
  ...arg: any[]
) => {
  if (!fn) {
    call(...arg)
  } else {
    if (typeof fn == 'function') {
      let result = fn(...arg)
      // 如果没有返回则不处理
      if (result == void 0) return
      // 是否为 boolean 类型
      if (Object.prototype.toString.call(result) === '[object Promise]') {
        result.then((res: any) => {
          call(res)
        })
      } else if (typeof result == 'boolean') {
        if (result) call()
      } else if (
        typeof result == 'object' ||
        typeof result == 'string' ||
        result instanceof Array
      ) {
        call(result)
      }
    }
  }
}
